import datetime
import pymysql
from dbutils.pooled_db import PooledDB


# 数据库连接配置
def getBetaConnection():
    pool = PooledDB(pymysql, 1, host='172.20.150.110', user='test_movie', passwd='test_movie154104',
                    db='cc_media_source', port=4308)
    conn = pool.connection()
    cur = conn.cursor()
    return conn, cur


def getProdConnection():
    pool = PooledDB(pymysql, 1, host='193.112.206.244', user='developer_read', passwd='developer_read#coocaa',
                    db='cc_media_source', port=3306)
    conn = pool.connection()
    cur = conn.cursor()
    return conn, cur


# 查询数据库获取maxId（带动态条件）
def get_max_id(cur, last_max_id=0):
    sql = f"""
    select max(tt.rt_id) maxId from (
        select t.* from rotate_topic_info t 
        where third_source = 'qqmusic' and type = 7 
        and (t.tag_name is null or t.tag_name = '' )  
        and t.rt_id > {last_max_id}  -- 动态条件：只查询比上次maxId大的记录
        order by t.rt_id limit 200
    ) tt
    """
    cur.execute(sql)
    result = cur.fetchone()
    return result[0] if result[0] else None

# 主函数
def main():
    # 使用测试库连接
    conn, cur = getProdConnection()

    try:
        last_max_id = 5536723    # 初始值，从0开始
        max_ids = []
        for i in range(18):
            # 查询数据库获取maxId（只查询比last_max_id大的记录）
            current_max_id = get_max_id(cur, last_max_id)

            if current_max_id is None:
                print(f"Iteration {i + 1}: No more records found (last_max_id={last_max_id}), stopping...")
                break

            print(f"Iteration {i + 1}: Found maxId = {current_max_id} (last_max_id={last_max_id})")

            # 异步调用接口（不等待结果）
            #call_api_async(current_max_id)
            max_ids.append(current_max_id)

            # 更新last_max_id为本次查询的maxId，以便下次查询使用
            last_max_id = current_max_id

        print(max_ids)


    finally:
        # 关闭数据库连接
        cur.close()
        conn.close()


if __name__ == "__main__":
    main()